package com.yst.feign2.interceptor;

import cn.hutool.core.lang.ObjectId;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 如果请求头中有trackId，认为为feign调用，设置tracId到当前日志参数中
 */
@Slf4j
@Component
public class TestInterceptor implements HandlerInterceptor, Ordered {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("TestInterceptor");
        String trackId = request.getHeader("trackId");
        if (trackId != null) {
            // 判断trackId是否是ObjectId
        } else {
            trackId = ObjectId.next();
        }
        MDC.put("trackId", trackId);
        return true;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
